package cn.pzhu.util;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by dongp on 2016/3/22.
 */
public class EncryptUtil {

    private static final char[] strHex = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};

    //创建签名charset加密模式如MD5
    public static String createSign(String content, String charset) {

        if(null == content || "".equals(content.trim())) {
            throw new IllegalArgumentException("签名参数不能为空");
        }
        return encrypt(content,charset);
    }

    //加密
    private static String encrypt(String content, String charset) {
        StringBuffer strb = new StringBuffer();
        try {
            MessageDigest messageDigest = MessageDigest.getInstance(charset);
            messageDigest.update(content.getBytes());
            byte[] buf = messageDigest.digest();
            for(int i = 0; i < buf.length; i++) {
                strb.append(toHex(buf[i] & 0xff));
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return strb.toString().toUpperCase();
    }

    //验签
    public static boolean checkSign(String content,String msg,String charset) {
        if(null == msg) {
            throw new IllegalArgumentException("密文不能为空");
        }
        return msg.equals(encrypt(content,charset));
    }

    private static String toHex(int b) {
        return String.valueOf(strHex[b/16]) + String.valueOf(strHex[b%16]);
    }

}